import datetime
import json
import time
import traceback

from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.core.cache import cache
from django.core.paginator import Paginator
from django.shortcuts import render
# Create your views here.
from django.utils.decorators import method_decorator
from rest_framework.response import Response
from rest_framework.views import APIView

from deviceManage import models
from deviceManage.seriallizers import DeviceTypeSeriallizer, DeviceSeriallizer, AlarmSeriallizer
from roomManage.views import imgType_list
from tools.authToken import create_token, userAuth, userCateAuth
from tools.encryption import getSha256
from tools.log import logger
from tools.tool import get_ip, get_json_values, get_uuid, get_file_type, get_time_uid, delete_file


# Create your views here.

# 设备类型
class DeviceType(APIView):
    @method_decorator(userAuth)
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.query_params.dict()

            all = get_json_values("all", body)
            if all:
                devices = models.DeviceType.objects.filter().order_by("sort")
                for device in devices:
                    li.append({
                        "id": device.id,
                        "name": device.name,
                    })
                resp = {"code": 1, "data": li}
                # resp = json.dumps(resp)
                return Response(resp)

            roomtypes = models.DeviceType.objects.filter().order_by("sort")

            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)
            paginator = Paginator(roomtypes, page_size)
            roomtypes = paginator.get_page(page_num)
            total = paginator.count

            seriallizer = DeviceTypeSeriallizer(roomtypes, many=True)
            resp = {"code": 1, "data": seriallizer.data, 'total':total}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator(userAuth)
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            body = json.loads(request.body)

            # body = request.POST.dict()
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            describe = get_json_values("describe", body, None)



            if models.DeviceType.objects.create(
                name=name,
                sort=sort,
                describe=describe,
            ):

                resp = {"code": 1, "data": li, "msg": '新建成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '新建失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator(userAuth)
    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            body = json.loads(request.body)
            id = get_json_values("id", body)
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            describe = get_json_values("describe", body, None)

            if models.DeviceType.objects.filter(id=id).update(
                name=name,
                sort=sort,
                describe=describe
            ):
                resp = {"code": 1, "data": li, "msg": '修改成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '修改失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator(userAuth)
    def delete(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = json.loads(request.body)
            id_list = get_json_values("id", body)
            # print(id_list)
            clothing = models.DeviceType.objects.filter(id__in=id_list)
            clothing.delete()

            resp = {"code": 1, "data": li,"msg": "删除成功"}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)



# 设备
class Device(APIView):

    @method_decorator([userAuth, userCateAuth])
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.query_params.dict()
            roomtypes = models.Device.objects.filter().order_by("sort", 'id')

            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)
            paginator = Paginator(roomtypes, page_size)
            roomtypes = paginator.get_page(page_num)
            total = paginator.count

            seriallizer = DeviceSeriallizer(roomtypes, many=True)
            resp = {"code": 1, "data": seriallizer.data, 'total': total}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator(userAuth, userCateAuth)
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.POST.dict()

            # body = json.loads(request.body)
            body = request.POST.dict()
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            type_id = get_json_values("type_id", body, None)
            room_id = get_json_values("room_id", body, None)
            ip = get_json_values("ip", body, None)

            uid = get_uuid()

            file = request.FILES.get("img", None)

            filepath = None
            # icon_type = ''
            # file_name = ''
            if file:
                file_nem, file_type = get_file_type(str(file))
                if file_type not in imgType_list:
                    li.append('不支持该格式')
                    resp = {"success": 0, "data": li}
                    return Response(resp)
                file_name = get_time_uid()
                filepath = '/{}/{}/{}'.format('media', 'device', file_name + file_type)
                openfile = settings.MEDIA_ROOT + '/device/' + file_name + file_type
                with open(openfile, 'wb+') as temp_file:
                    for chunk in file.chunks():
                        temp_file.write(chunk)

            if models.Device.objects.create(
                name=name,
                sort=sort,
                uuid=uid,
                type_id=type_id,
                room_id=room_id,
                ip=ip,
                icon=filepath
            ):

                resp = {"code": 1, "data": li, "msg": '新建成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '新建失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth,userCateAuth])
    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            # body = json.loads(request.body)
            body = request.POST.dict()
            id = get_json_values("id", body)
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            type_id = get_json_values("type_id", body, None)
            room_id = get_json_values("room_id", body, None)
            ip = get_json_values("ip", body, None)

            file = request.FILES.get("img", None)
            filepath = None
            # icon_type = ''
            # file_name = ''
            item = models.Device.objects.filter(id=id)
            if file:
                file_nem, file_type = get_file_type(str(file))
                if file_type not in imgType_list:
                    li.append('不支持该格式')
                    resp = {"success": 0, "data": li}
                    return Response(resp)
                file_name = get_time_uid()
                filepath = '/{}/{}/{}'.format('media', 'device', file_name + file_type)
                openfile = settings.MEDIA_ROOT + '/device/' + file_name + file_type
                with open(openfile, 'wb+') as temp_file:
                    for chunk in file.chunks():
                        temp_file.write(chunk)
                item.update(
                    icon=filepath
                )

            if item.update(
                name=name,
                sort=sort,
                type_id=type_id,
                room_id=room_id,
                ip=ip
            ):
                resp = {"code": 1, "data": li, "msg": '修改成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '修改失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth,userCateAuth])
    def delete(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = json.loads(request.body)
            id_list = get_json_values("id", body)
            # print(id_list)
            devices = models.Device.objects.filter(id__in=id_list)
            for rm in devices:
                if rm.icon:
                    delete_file(settings.BASE_DIR+rm.icon)
            devices.delete()

            resp = {"code": 1, "data": li,"msg": "删除成功"}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)


# 告警

class Alarm(APIView):

    @method_decorator(userAuth)
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            # ip = get_ip(request)
            body = request.query_params.dict()
            recor = get_json_values('recor', body)
            search_dict = {}
            if recor:
                search_dict['recovertime'] = None
                roomtypes = models.Alarm.objects.filter(**search_dict).order_by("-createtime")
                seriallizer = AlarmSeriallizer(roomtypes, many=True)
                resp = {"code": 1, "data": seriallizer.data}
                return Response(resp)

            roomtypes = models.Alarm.objects.filter().order_by("-createtime")

            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)
            paginator = Paginator(roomtypes, page_size)
            roomtypes = paginator.get_page(page_num)
            total = paginator.count

            seriallizer = AlarmSeriallizer(roomtypes, many=True)
            resp = {"code": 1, "data": seriallizer.data, 'total': total}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth,userCateAuth])
    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            body = json.loads(request.body)
            # body = request.POST.dict()
            id = get_json_values("id", body)

            item = models.Alarm.objects.filter(id=id)
            now_time = datetime.datetime.now()
            if item.update(
                recovertime=now_time
            ):
                resp = {"code": 1, "data": li, "msg": '手动恢复成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '手动恢复失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

# 设备统计
class GetDeviceCount(APIView):

    @method_decorator(userAuth)
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.query_params.dict()
            device = models.Device.objects.filter()
            total = device.count()
            online = device.filter(online=1,room__status=1).count()
            offline = total-online
            li.append({
                'total':total,
                'online':online,
                'offline':offline
            })

            resp = {"code": 1, "data": li}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)


class GetRoomDevice(APIView):

    @method_decorator(userAuth)
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.query_params.dict()
            roomId = get_json_values('roomId', body)

            search_dict = {}
            if roomId:
                search_dict['room_id'] = roomId

            device = models.Device.objects.filter(**search_dict).order_by('sort')
            # print(device)
            seriallizer = DeviceSeriallizer(device, many=True)
            resp = {"code": 1, "data": seriallizer.data}

        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)


def create_alarm(device_id, reason):
    # print('create alarm')
    alarm = models.Alarm(
        device_id=device_id,
        reason=reason,
    )
    alarm.save()
